<template>
  <!-- 单选框 -->
  <el-radio-group v-if="tagType === 'radio'" :value="getValueString" :disabled="disabled" @click.native="handleChange">
    <el-radio v-for="(item,key) in dictOptions" :key="key" :label="item.dictValue">
      {{ item.dictLabel }}
    </el-radio>
  </el-radio-group>

  <!-- 按钮样式单选 -->
  <el-radio-group v-else-if="tagType === 'radioButton'" :value="getValueString" :disabled="disabled" @click.native="handleChange">
    <el-radio-button v-for="(item,key) in dictOptions" :key="key" :label="item.dictValue">
      {{ item.dictLabel }}
    </el-radio-button>
  </el-radio-group>

  <!-- 选择器 -->
  <el-select v-else-if="tagType === 'select'" :value="getValueString" :filterable="filterable" style="width:100%" :placeholder="placeholder" :disabled="disabled" @change="handleChange">
    <el-option v-for="item in dictOptions" :key="item.dictValue" :label="item.dictLabel" :value="item.dictValue" />
  </el-select>
</template>

<script>
export default {
  name: 'ZrkDictSelectTag',
  props: {
    value: {
      type: [String, Number],
      default: undefined
    },
    // 字典编码
    dictCode: {
      required: true,
      type: String,
      default: ''
    },
    placeholder: {
      type: String,
      default: '请选择'
    },
    disabled: {
      type: Boolean,
      default: false
    },
    triggerChange: {
      type: Boolean,
      default: false
    },
    // 是否开启搜索
    filterable: {
      type: Boolean,
      default: false
    },
    // 字典类型 select 选择框 radio 单选框 radioButton 按钮样式单选
    type: {
      type: String,
      default: 'select'
    }
  },
  data() {
    return {
      dictOptions: []
    }
  },
  computed: {
    getValueString() {
      return this.value != null ? this.value.toString() : undefined
    }
  },
  watch: {
    dictCode: {
      immediate: true,
      handler() {
        this.initDictData()
      }
    }
  },
  created() {
    this.tagType = this.type
  },
  methods: {
    // 根据字典编码，初始化字典数组
    initDictData() {
      this.getDicts(this.dictCode).then((response) => {
        this.dictOptions = response.data
      })
    },
    handleChange(e) {
      let val
      /**
       * 踩坑点
       * element radio @change 事件无法正确获取label下的value值
       * 只能通过@click.native 事件获取e.target.value
       * @click.native方法因为element组件二次封装冒泡会执行两次。
       */
      if (this.tagType.indexOf('radio') !== -1) {
        if (typeof e.target.value !== 'undefined') val = e.target.value
      } else {
        val = e
      }
      if (this.triggerChange) {
        this.$emit('change', val)
        return
      }
      this.$emit('input', val)
    }
  }
}
</script>
